﻿using AutoMapper;
using Enum;
using MediatR;
using Practice.Common.DbCont;
using Practice.Common.Domains;
using Practice.Common.Dto;
using Practice.Common.Infrastructure.Interfaces;

namespace Practice.API.Application.Commands.Permissionw
{
    public class PermissionCreateHandler : IRequestHandler<PermissionCreateCommand, Result>
    {
        public readonly IBaseRepository<Permission> UPermissionRepository;
        public readonly IMapper _mapper;
        public readonly ILogger<PermissionCreateHandler> logger;

        public PermissionCreateHandler(IBaseRepository<Permission> uPermissionRepository, IMapper mapper, ILogger<PermissionCreateHandler> logger)
        {
            UPermissionRepository = uPermissionRepository;
            _mapper = mapper;
            this.logger = logger;
        }

        public async Task<Result> Handle(PermissionCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.Added };

            try
            {
                Permission users = _mapper.Map<Permission>(request);
                var res = UPermissionRepository.Add(users);
                if (res > 0)
                {
                    result.Code = (int)CommonEnumCode.Success;
                }
            }
            catch (Exception ex)
            {
                logger.LogError("添加失败" + ex.Message);
                result.Msg = "添加失败";
            }
            finally
            {
                logger.LogInformation("权限添加成功");
            }
            return result;
        }

    }
}
